package cn.wm.netty01.chat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

public class ChatServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush(Unpooled.copiedBuffer("[客户端]" + ctx.channel().remoteAddress() + " 上线了。。。" +
                LocalDateTime.now().toString() + "\n", CharsetUtil.UTF_8));
        channelGroup.add(ctx.channel());
        System.out.println(ctx.channel().remoteAddress()+"上线了...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush(Unpooled.copiedBuffer("[客户端]" + ctx.channel().remoteAddress() + " 下线了。。。" +
                LocalDateTime.now().toString() + "\n", CharsetUtil.UTF_8));
        System.out.println(ctx.channel().remoteAddress() + " 下线了" + "\n");
        System.out.println("channelGroup size=" + channelGroup.size());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        channelGroup.forEach(channel -> {
            if (channel != ctx.channel()) {
                channel.writeAndFlush(Unpooled.copiedBuffer("客户端[" + channel.remoteAddress() + "]发送了消息：" + ((ByteBuf) msg).toString(CharsetUtil.UTF_8) + "\n", CharsetUtil.UTF_8));
            } else {
                channel.writeAndFlush(Unpooled.copiedBuffer("自己[" + channel.remoteAddress() + "]发送了消息：" + ((ByteBuf) msg).toString(CharsetUtil.UTF_8) + "\n", CharsetUtil.UTF_8));
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //关闭通道
        ctx.close();
    }
}
